package pres.man.interview.producerconsumer.signleton;

import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * 生产者消费者问题
 * 采用阻塞队列来解决
 *
 * @author MAN
 * @date 2020-12-04 21:23
 * @project
 * @since
 */
public class Queue {


    private static final BlockingQueue<Integer> QUEUE = new ArrayBlockingQueue(5);
    private static volatile AtomicInteger COUNT = new AtomicInteger(0);
    private static final ThreadPoolExecutor POOL = new ThreadPoolExecutor(5, 8, 20, TimeUnit.SECONDS, new ArrayBlockingQueue<>(10), new ThreadPoolExecutor.CallerRunsPolicy());

    public static void main(String[] args) {
        for (int i = 0; i < 2; i++) {
            POOL.execute(() -> {
                for (; ; ) {
                    product();
                    try {
                        TimeUnit.SECONDS.sleep(1);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            });
            POOL.execute(() -> {
                for (; ; ) {
                    consume();
                    try {
                        TimeUnit.SECONDS.sleep(1);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            });
        }
    }

    private static void product() {
        if (QUEUE.offer(COUNT.incrementAndGet())) {
            System.out.println("生产一个东西，此时有" + QUEUE.size() + "个东西");
        }
    }

    private static void consume() {
        if (QUEUE.poll() != null) {
            System.out.println("消费一个东西，此时有" + QUEUE.size() + "个东西");
        }
    }
}
